package com.stockz.equity.charting.view.widget;


import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JPopupMenu;

import org.metawidget.swing.SwingMetawidget;
import org.metawidget.swing.widgetprocessor.binding.beanutils.BeanUtilsBindingProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.stockz.equity.charting.display.Displayable;
import com.stockz.equity.charting.event.EventPublisher;
import com.stockz.equity.charting.event.RepaintStockChartPanelEvent;
import com.stockz.equity.charting.view.StockChartView;

@Component
public class EditIndicatorPopupMenu extends JPopupMenu{
	private static final long serialVersionUID = -1653242974079804367L;

	@Autowired
	private StockChartView stockChartView;
	
	private EditIndicatorPopupMenu instance;
	private Displayable displayable;
	private SwingMetawidget swingMetaWidget = new SwingMetawidget();
	private BeanUtilsBindingProcessor beanUtilsBindingProcessor = new BeanUtilsBindingProcessor();
	private JButton editButton = new JButton("Edit");
	private ActionListener editButtonActionListener = new ActionListener(){
		@Override
		public void actionPerformed(ActionEvent e) {
			swingMetaWidget.getWidgetProcessor(BeanUtilsBindingProcessor.class).save(swingMetaWidget);
			displayable.refreshValues();
			instance.setVisible(false);
			EventPublisher.publishEvent(
					new RepaintStockChartPanelEvent(
							stockChartView.getSelectedStockChart().getStockChartPanel()));
		}
	};
	
	public EditIndicatorPopupMenu(){
		editButton.addActionListener(editButtonActionListener);
		swingMetaWidget.addWidgetProcessor(beanUtilsBindingProcessor);	
		instance = this;
	}

	@Override
	public void show(java.awt.Component invoker, int x, int y) {
		swingMetaWidget.setToInspect(displayable.getConfiguration());
		swingMetaWidget.add(editButton);
		add(swingMetaWidget);
		super.show(invoker, x, y);
	}
	
	public Displayable getDisplayable() {
		return displayable;
	}

	public void setDisplayable(Displayable displayable) {
		this.displayable = displayable;
	}
}
